package com.simple.weibo.service;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import com.simple.weibo.receiver.DownPicReceiver;

import java.io.*;
import java.net.URL;

/**
 * @author mxf <a href="mailto:maxuefengs@gmail.com">mxf</a>
 *         11-8-17 上午10:54
 * @since version 1.0
 */
public class DownPicService extends Service {
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startDownload(intent.getStringExtra("url"));
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void startDownload(final String url) {
        new Thread(new Runnable() {
            public void run() {
                downLoad(url);
            }
        }).start();
    }

    private void downLoad(String url) {
        InputStream is = null;
        OutputStream os = null;
        String fileName = null;
        try {
            is = new URL(url).openStream();

            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/simpelweibo";
            } else {
                fileName = Environment.getRootDirectory().getAbsolutePath() + "/simpelweibo" ;
            }
            File f = new File(fileName);
            if(!f.exists()){
                 f.mkdirs();
            }
            fileName += url.substring(url.lastIndexOf("/"), url.length());
            os = new FileOutputStream(fileName);

            byte[] b = new byte[1024 * 5];
            int c;
            while ((c = is.read(b)) != -1) {
                os.write(b, 0, c);
            }
            Intent intent = new Intent(this, DownPicReceiver.class);
            intent.putExtra("name", fileName);
            sendBroadcast(intent);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
